package dome.common;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class FileUtils {
    public static void writeObject(String filename, Map map) {
        try {
            File file = new File(filename);
            if (file.exists()) {//如果文件不存在，创立一个新文件
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(map);
            oos.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public static Map readMapObject(String filename) {
        Map map;
        try {
            File file = new File(filename);
            map = null;
            if (file.length() == 0) {
                map = new HashMap<>();
            } else {
                FileInputStream fis = new FileInputStream(file);
                ObjectInputStream ois = new ObjectInputStream(fis);
                map = (Map) ois.readObject();
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return map;
    }
}
